package com.atguigu.jdbc;

import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CRUDDemo2 {
    //表中添加数据
    @Test
    public void test() throws SQLException {
        Connection connection = JDBCUtils2.getConnect();
        String sql = "insert into demo1(id,username) values(?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(2,"ff");
        ps.setInt(1,111);
        int i = ps.executeUpdate();
        System.out.println("有"+i+"修改成功");
        JDBCUtils2.close(connection,ps);
    }
    //表中修改数据
    @Test
    public void test1(){

    }
    //遍历查询数据

    @Test
    public void test2() throws SQLException {
        List<Student> resultSet = getResultSet();
        for (Student student : resultSet) {
            System.out.println(student);
        }
    }
    //表中查询数据
    public   List<Student> getResultSet() throws SQLException {
        List<Student> list = new ArrayList<>();
        Connection connect = JDBCUtils2.getConnect();
        String sql = "select * from demo1";
        PreparedStatement ps = connect.prepareStatement(sql);
        ResultSet resultSet = ps.executeQuery();
        while(resultSet.next()){
            int id = resultSet.getInt("id");
            String username = resultSet.getString("username");
            list.add(new Student(id,username));
        }
        JDBCUtils2.close(connect,ps,resultSet);
        return list;
    }
}


